<template>
  <el-dialog
    :modelValue="visible"
    @update:modelValue="$emit('update:visible', $event)"
    title="添加膳食记录"
    width="600px"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item label="餐次">
        <el-select v-model="form.mealType" style="width: 100%">
          <el-option
            v-for="type in mealTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
            @click="form.recordTime = type.time"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="时间">
        <el-time-picker
          v-model="form.recordTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择时间"
          style="width: 100%"
        />
      </el-form-item>

      <div v-if="selectedFoods.length" class="selected-foods">
        <h4>已选食物</h4>
        <el-table :data="selectedFoods" style="width: 100%">
          <el-table-column prop="food.name" label="食物名称" />
          <el-table-column prop="quantity" label="数量" width="120">
            <template #default="{ row }">
              {{ row.quantity }}{{ row.food.unit }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ $index }">
              <el-button type="danger" link @click="removeFood($index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-form-item label="食物分类">
        <el-select 
          v-model="selectedCategory"
          placeholder="选择食物分类"
          style="width: 100%"
        >
          <el-option
            v-for="category in categories"
            :key="category"
            :label="category"
            :value="category"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="食物">
        <el-select
          v-model="form.foodId"
          placeholder="选择食物"
          style="width: 100%"
          @change="handleFoodChange"
        >
          <el-option
            v-for="food in foodList"
            :key="food.foodId"
            :label="food.name"
            :value="food.foodId"
          >
            <div class="food-option">
              <el-avatar 
                :size="32" 
                :src="food.imageUrl"
                :fallback="defaultFoodImage"
                fit="cover"
                class="food-avatar"
                style="min-width: 32px; min-height: 32px;"
              />
              <div class="food-info">
                <span class="food-name">{{ food.name }}</span>
                <small class="food-calories">{{ food.calories }}千卡/{{ food.unit }}</small>
              </div>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="数量">
        <el-input-number
          v-model="form.quantity"
          :min="0.1"
          :step="0.1"
          :precision="1"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="addToList">
          添加到列表
        </el-button>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm"
          :disabled="selectedFoods.length === 0"
        >
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import request from '@/config/axios'
import { ElMessage } from 'element-plus'

const mealTypes = [
  { label: '早餐', value: '早餐', time: '08:00' },
  { label: '午餐', value: '午餐', time: '12:00' },
  { label: '晚餐', value: '晚餐', time: '18:00' },
  { label: '零食', value: '零食', time: '15:00' }
]

defineProps({
  visible: Boolean
})

const emit = defineEmits(['update:visible', 'confirm'])

const categories = ref([])
const foodList = ref([])
const selectedCategory = ref('')
const selectedFood = ref(null)
const selectedFoods = ref([])

const form = ref({
  mealType: '早餐',
  recordTime: '08:00',
  foodId: null,
  quantity: 1,
  food: null
})

const defaultFoodImage = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')

// 获取食物分类
const fetchCategories = async () => {
  try {
    const response = await request({
      url: '/api/food/categories',
      method: 'get'
    })
    if (response?.success) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取食物分类失败:', error)
  }
}

// 根据分类获取食物列表
const fetchFoodsByCategory = async (category) => {
  try {
    const response = await request({
      url: `/api/food/category/${category}`,
      method: 'get'
    })
    if (response?.success) {
      foodList.value = response.data
    }
  } catch (error) {
    console.error('获取食��列表失败:', error)
  }
}

// 监听分类变化
watch(selectedCategory, (newCategory) => {
  if (newCategory) {
    fetchFoodsByCategory(newCategory)
  }
})

// 处理食物选择
const handleFoodChange = (foodId) => {
  selectedFood.value = foodList.value.find(food => food.foodId === foodId)
  if (selectedFood.value) {
    form.value.food = selectedFood.value
  }
}

const addToList = () => {
  if (!form.value.foodId || !form.value.quantity) {
    ElMessage.warning('请选择食物并填写数量')
    return
  }
  selectedFoods.value.push({
    foodId: form.value.foodId,
    quantity: form.value.quantity,
    food: form.value.food
  })
  // 重置食物选择和数量
  form.value.foodId = null
  form.value.quantity = 1
  form.value.food = null
  selectedFood.value = null
}

const removeFood = (index) => {
  selectedFoods.value.splice(index, 1)
}

const handleCancel = () => {
  emit('update:visible', false)
  resetForm()
}

const resetForm = () => {
  form.value = {
    mealType: '早餐',
    recordTime: '08:00',
    foodId: null,
    quantity: 1,
    food: null
  }
  selectedCategory.value = ''
  selectedFood.value = null
  selectedFoods.value = []
}

const handleConfirm = () => {
  if (selectedFoods.value.length === 0) {
    ElMessage.warning('请至少添加一种食物')
    return
  }
  emit('confirm', {
    mealType: form.value.mealType,
    recordTime: form.value.recordTime,
    details: selectedFoods.value
  })
  emit('update:visible', false)
  resetForm()
}

// 初始化时获取分类
fetchCategories()
</script>

<style scoped>
.food-selector {
  padding: 1rem;
}

.food-option {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 4px 0;
  height: 40px;
}

.food-avatar {
  flex-shrink: 0;
  border: 1px solid var(--el-border-color-lighter);
  background-color: var(--el-fill-color-light);
  display: flex;
  align-items: center;
  justify-content: center;
}

.food-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  min-width: 0;
  justify-content: center;
}

.food-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.food-calories {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.nutrition-preview {
  margin-top: 1.5rem;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
  padding: 1rem;
  background: var(--el-fill-color-light);
  border-radius: 8px;
}

.nutrition-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.label {
  color: var(--el-text-color-secondary);
  font-size: 0.9rem;
}

.value {
  margin-top: 0.25rem;
  font-weight: 600;
  color: var(--el-color-primary);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

@media (max-width: 768px) {
  .nutrition-preview {
    grid-template-columns: repeat(2, 1fr);
  }
}

.selected-foods {
  margin: 1rem 0;
  padding: 1rem;
  background: var(--el-fill-color-light);
  border-radius: 4px;
}

.selected-foods h4 {
  margin: 0 0 1rem;
  color: var(--el-text-color-primary);
}

:deep(.el-select-dropdown__item) {
  padding: 0 12px;
}
</style> 